﻿Imports DevComponents.AdvTree
Imports HTLibrary
Imports TNCBAL
Imports TNCDAL

Public Class ucAdvanceDriverManagement
    Private _objAdvanceDriverController As New AdvanceDriverController
    Private _objCurrAdvanceDriver As tblAdvanceDriver

    Public Sub New()
        InitializeComponent()

        TextBoxHelper.TextBox_InitUpperStringEvent(Me.Controls)
        'CollectionHelper.TextBox_InitNumberEvent(Me.Controls, New List(Of String)(New String() {txtAmount.Name}))
        InitCommands()
    End Sub

    Private Sub ucAdvanceDriverManagement_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            InitFormData()

            BindDataGridView()
            FormatGridView()
        Catch ex As Exception

        End Try
    End Sub

    Public Sub BindDataGridView(Optional ByVal indexRow As Integer = -1)
        'If cmbMonths.Text = "" Or advTreeDrivers.SelectedValue Is Nothing Then
        '    Exit Sub
        'End If
        Dim amount As Double = 0
        Dim query As IQueryable = _objAdvanceDriverController.SelectAllRecord_Custom(cmbMonths.Text, advTreeDrivers.SelectedValue, amount)
        ToolStripTextBoxAmount.Text = CollectionHelper.FormatQuantityStyle(amount)

        Dim source As New BindingSource
        source.DataSource = query
        gridView.DataSource = source
        BindingNavigator1.BindingSource = source
        If indexRow > 0 Then
            'Set current row
            'dataGridView.Rows(indexRow).Selected = True
            'dataGridView.FirstDisplayedScrollingRowIndex = indexRow
            For Each col As DataGridViewColumn In gridView.Columns
                If col.Visible Then
                    gridView.CurrentCell = gridView.Rows(indexRow).Cells(col.Index)
                    Exit For
                End If
            Next
        End If

        'Nếu không tồn tại row nào
        If gridView.Rows.Count = 0 Then
            ResetControls() 'reset hết các control
        End If
        'disable 2 nút edit và delete nếu row count = 0
        _ucCommands.EnableButtons(False, gridView.Rows.Count)


    End Sub

    Public Sub FormatGridView()
        Dim hideColumns As New List(Of String)({"Id_AdvanceDriver"})
        Dim numberColumns As New List(Of String)({"Amount"})
        CViewer.FormatDataGridView(gridView, _
                                   hideColumns, _
                                   Nothing, _
                                   Nothing, _
                                   numberColumns)
    End Sub

    Public Sub LoadForm()
        'show result
        dtDate.Value = _objCurrAdvanceDriver.AdvanceDate.Value.Date
        txtAmount.Text = CollectionHelper.FormatQuantityStyle(_objCurrAdvanceDriver.Amount)
    End Sub

    ''' <summary>
    ''' Khởi tạo dữ liệu mặc định cho các control
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub InitFormData()
        HTLibrary.DataGridViewHelper.DataGridView_InitEvent(gridView)
        'Load danh sách Month
        For i As Integer = 1 To Now.Month
            cmbMonths.Items.Add(i)
        Next
        cmbMonths.SelectedIndex = Now.Month - 1

        'Load danh sách Driver
        CViewer.BindingAdvTreeView_Drivers(advTreeDrivers)
        For Each node As Node In advTreeDrivers.Nodes
            node.Image = ImageList1.Images(0)
        Next
    End Sub

    ''' <summary>
    ''' Lưu dữ liệu trên form vào object
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub GetInfoByForm()
        With _objCurrAdvanceDriver
            .AdvanceDate = dtDate.Value
            Try
                'Nếu không phải ngày thì gán null
                If .AdvanceDate.Value = "#12:00:00 AM#" Then
                    .AdvanceDate = Nothing
                Else
                    .AdvanceDate = dtDate.Value
                End If
            Catch ex As Exception
                .AdvanceDate = Nothing
            End Try

            Try
                .ID_Driver = advTreeDrivers.SelectedValue
            Catch ex As Exception
                '.tblDriver = advTreeDrivers.SelectedItem
                Throw ex
            End Try

            .Amount = Double.Parse(txtAmount.Text)
        End With
    End Sub

    Public Sub ResetControls()
        CViewer.ResetControls(Me.ExpandablePanelDetails.Controls)

        'Init obj
        _objCurrAdvanceDriver = New tblAdvanceDriver
        dtDate.Value = Date.Now
    End Sub

#Region "Commands"
    ''' <summary>
    ''' Init commands
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub InitCommands()
        Dim controlCollect As New List(Of Control)
        controlCollect.Add(PanelEx2)
        '_ucCommands = New ucCommands(Me, controlCollect)
        _ucCommands.InitControl(Me, controlCollect)
        _ucCommands.ShowHideButtons(True, True, True)
        _ucCommands.btnAddEvent_Click = New EventHandler(AddressOf btnAdd_Click)
        _ucCommands.btnEditEvent_Click = New EventHandler(AddressOf btnEdit_Click)
        _ucCommands.btnDeleteEvent_Click = New EventHandler(AddressOf btnDel_Click)
        _ucCommands.btnUpdateEvent_Click = New EventHandler(AddressOf btnUpdate_Click)
        _ucCommands.btnCancelEvent_Click = New EventHandler(AddressOf btnCancel_Click)
        _ucCommands.Dock = DockStyle.Fill
        PanelExCommand.Controls.Add(_ucCommands)
    End Sub

    Public Sub FocusControl()
        dtDate.Focus()
    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        ResetControls()
        FocusControl()
    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        FocusControl()
    End Sub

    Private Sub btnDel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If MessageBox.Show("Delete this record?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
            Try
                'Write log
                Dim objLogController As New LogController
                objLogController.Insert(enumAction.Delete, String.Format("Advance Driver {0} on {1}", _objCurrAdvanceDriver.tblDriver.DriverName, _objCurrAdvanceDriver.AdvanceDate))

                Dim indexRow As Integer = gridView.CurrentRow.Index - 1
                _objAdvanceDriverController.Delete(_objCurrAdvanceDriver)

                BindDataGridView(indexRow)
            Catch ex As Exception
#If DEBUG Then
                Throw ex
#Else
                MessageBox.Show(ex.Message)
#End If
            End Try

        End If
    End Sub

    Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            ErrorProvider1.Clear()
            'Kiểm tra tính hợp lệ của việc nhập dữ liệu
            If Not Me.ValidateChildren(ValidationConstraints.Enabled) Then
                _ucCommands.EnableButtons(True)
                Exit Sub
            End If

            GetInfoByForm()

            Dim action As enumAction
            Dim indexRow As Integer = -1
            If _objCurrAdvanceDriver.ID_AdvanceDriver > 0 Then
                _objAdvanceDriverController.Update(_objCurrAdvanceDriver)
                action = enumAction.Edit
                indexRow = gridView.CurrentRow.Index
            Else
                _objAdvanceDriverController.Insert(_objCurrAdvanceDriver)
                action = enumAction.Add
                indexRow = gridView.Rows.Count
            End If
            'Write log
            Dim objLogController As New LogController
            objLogController.Insert(action, String.Format("Advance Driver {0} on {1}", _objCurrAdvanceDriver.tblDriver.DriverName, _objCurrAdvanceDriver.AdvanceDate))
            'Refresh gridview
            BindDataGridView(indexRow)
        Catch ex As Exception
#If DEBUG Then
            Throw ex
#Else
            MessageBox.Show(ex.Message)
#End If
        End Try
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        dataGridView_CurrentCellChanged(Nothing, Nothing)
    End Sub

    Private Sub dataGridView_CurrentCellChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gridView.CurrentCellChanged
        'Load info
        Try
            If _ucCommands Is Nothing Then
                Return
            End If

            If gridView.CurrentRow Is Nothing Then
                Return
            End If

            'Kiểm tra nếu đang cập nhật/thêm mới thì không hiển thị dữ liệu
            If _ucCommands.btnUpdate.Enabled Then
                Return
            End If

            'Lấy ID
            Dim id As Integer = gridView.CurrentRow.Cells("ID_AdvanceDriver").Value
            _objCurrAdvanceDriver = _objAdvanceDriverController.SelectRecordById(id)

            'Fill company's fields
            LoadForm()

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
#End Region

    Private Sub dtDate_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dtDate.KeyDown
        If e.KeyCode = Keys.Delete Then
            CType(sender, DevComponents.Editors.DateTimeAdv.DateTimeInput).Value = Nothing
        End If
    End Sub

    Private Sub dtDate_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles dtDate.Validating
        Dim cancel As Boolean = False
        'Nếu không phải ngày thì gán null
        If dtDate.Value = "#12:00:00 AM#" Then
            cancel = True
            Me.ErrorProvider1.SetError(dtDate, "Chưa nhập ngày!")
        End If
        e.Cancel = cancel
    End Sub

    'Private Sub cmbDriver_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs)
    '    Dim cancel As Boolean = False
    '    If cmbDriver.SelectedValue Is Nothing Then
    '        cancel = True
    '        Me.ErrorProvider1.SetError(cmbDriver, "Chưa chọn tài xế!")
    '    End If
    '    e.Cancel = cancel
    'End Sub

    Private Sub txtAmount_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtAmount.Validating
        Dim cancel As Boolean = False
        If String.IsNullOrEmpty(txtAmount.Text) Then
            cancel = True
            Me.ErrorProvider1.SetError(txtAmount, "Chưa nhập số tiền!")
        Else
            Try
                Dim value As Double = Double.Parse(txtAmount.Text)
                If value < 0 Then
                    cancel = True
                    Me.ErrorProvider1.SetError(txtAmount, "Số tiền phải >= 0")
                End If
            Catch ex As Exception
                cancel = True
                Me.ErrorProvider1.SetError(txtAmount, "Phải là giá trị số!")
            End Try
        End If

        If cancel = True Then
            txtAmount.Focus()
        End If

        e.Cancel = cancel
    End Sub

    'Private Sub cmbDriver_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    If cmbDriver.Text <> "" Then
    '        Dim objDriverController As New MDrivers
    '        Try
    '            cmbDriver.SelectedValue = objDriverController.SelectRecordByName(cmbDriver.Text).ID_Driver
    '        Catch ex As Exception
    '            cmbDriver.Text = ""
    '        End Try
    '    End If
    'End Sub

    Private Sub txtAmount_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtAmount.Leave
        Try
            txtAmount.Text = CollectionHelper.FormatQuantityStyle(Double.Parse(txtAmount.Text))
        Catch ex As Exception
            txtAmount.Text = ""
        End Try
    End Sub

    Private Sub dtDate_Validated(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtDate.Validated
        ErrorProvider1.SetError(dtDate, "")
    End Sub

    'Private Sub cmbDriver_Validated(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    ErrorProvider1.SetError(cmbDriver, "")
    'End Sub

    Private Sub txtAmount_Validated(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtAmount.Validated
        ErrorProvider1.SetError(txtAmount, "")
    End Sub

    Private Sub cmbMonths_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbMonths.SelectedIndexChanged
        Try
            If cmbMonths.Text <> "" Then
                BindDataGridView()
            End If
        Catch ex As Exception

        End Try
        

    End Sub

    Private Sub advTreeDrivers_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles advTreeDrivers.SelectedIndexChanged
        Try
            If advTreeDrivers.SelectedValue IsNot Nothing Then
                BindDataGridView()
            End If
        Catch ex As Exception

        End Try
        
    End Sub

    'Private Sub gridView_RowPostPaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles gridView.RowPostPaint
    '    Dim grid = CType(sender, DataGridView)
    '    Dim rowIdx = (e.RowIndex + 1).ToString()

    '    Dim centerFormat = New StringFormat()
    '    With centerFormat
    '        ' right alignment might actually make more sense for numbers
    '        .Alignment = StringAlignment.Center
    '        .LineAlignment = StringAlignment.Center
    '    End With

    '    Dim headerBounds = New Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height)
    '    e.Graphics.DrawString(rowIdx, Me.Font, SystemBrushes.ControlText, headerBounds, centerFormat)
    'End Sub
End Class
